package com.sdnu.iosclub.qvs.listener;

import com.rabbitmq.client.Channel;
import com.sdnu.iosclub.qvs.entity.QvsResult;
import com.sdnu.iosclub.qvs.entity.QvsText;
import com.sdnu.iosclub.qvs.service.QvsResultService;
import com.sdnu.iosclub.qvs.service.QvsTextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @Author: Zhao YunLai
 * @Date: 2022/09/22/21:43
 * @Description:
 */
@Component
@Slf4j
public class QvsMQListener {

    @Autowired
    private QvsResultService qvsResultService;

    @Autowired
    private QvsTextService qvsTextService;

    //监听填空题结果的队列
    @RabbitListener(queues = {"${mq.queue.text}"})
    //后面两个参数可以不写，一般只要msg即可，第一个参数为传递的消息，类型和生产者传递的一致
    public void receiveQvsTextList(List<QvsText> list, Channel channel, Message message) throws IOException {
        try{
            //处理，一次取一条数据
            boolean b = qvsTextService.saveBatch(list);
            if(!b){
                log.warn("批量保存失败一次");
            }
            ////确认消息发送成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("消费处理异常：{}",e.getMessage());
            ////拒绝当前消息，并把消息返回原队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }

    //监听选择题结果的队列
    @RabbitListener(queues = {"${mq.queue.result}"})
    public void receiveQvsResultList(List<QvsResult> list,Channel channel,Message message) throws IOException {
        try{
            //处理，一次取一条数据
            boolean b = qvsResultService.saveBatch(list);
            if(!b){
                log.warn("批量保存失败一次");
            }
            ////确认消息发送成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("消费处理异常：{}",e.getMessage());
            ////拒绝当前消息，并把消息返回原队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}
